<template>
    <div id="login">
        <div class="app-container" style="background-color: #344a5f">
            <!--表单按钮-->
            <ul class="menu-tab">
                <li v-for="(item, index) in menuTab" :key="index" :class="{ 'current': item.isCurrent }"
                    @click="toggleMenu(item)">
                    {{ item.txt }}
                </li>
            </ul>


            <!--表单内容-->
            <el-form :model="loginForm" status-icon :rules="rules" ref="loginFromRef" class="login-form" size="medium">
                <el-form-item prop="userName" class="login-form-item">
                    <label for="userName">账号</label>
                    <el-input id="userName"  v-model="loginForm.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="passWord" class="login-form-item">
                    <label for="passWord">密码</label>
                    <el-input id="passWord" type="passWord" v-model="loginForm.passWord" ></el-input>
                </el-form-item>
                <el-form-item prop="passWordRepeat" class="login-form-item" v-show='model === "register"'>
                    <label for="passWordRepeat">重复密码</label>
                    <el-input id="passWordRepeat" type="passWord" v-model="loginForm.passWordRepeat"
                        autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="code" class="login-form-item">
                    <label for="code">验证码</label>
                    <el-row :gutter="10">
                        <el-col :span="15">
                            <el-input id="code" type="text" v-model="loginForm.code" autocomplete="off" minlength="6"
                                maxlength="6"></el-input>
                        </el-col>
                        <el-col :span="9">
                            <el-button class="block" type="success" @click="getSms()" :disabled="codeButton.disabled">{{
                                codeButton.text }}</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button class="block login-btn" type="danger" @click="submitForm('loginForm')"
                        :disabled="false">{{ model === 'login' ?
                            "登录" : "注册" }}
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>
<script setup>
import {login} from '../../api/request.js'
import { ref, reactive } from 'vue'
import { emailRule, passwordRule, codeRule } from "../../utils/validate"
import { useRouter } from "vue-router"
import { ElMessage } from 'element-plus'
//定义router对象
const router=useRouter()

const input = ref('')
const loginFromRef = ref(null)



// 验证邮箱、密码、重复密码、验证码
let validateEmail = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('邮箱不能为空'));
    } else if (emailRule(value)) {
        return callback(new Error('邮箱格式有误'));
    } else {
        callback()
    }
};
//验证用户名
let validateUserName = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('用户名不能为空'));
    } else {
        callback()
    }
};
let validatePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'));
    }  else {
        callback();
    }
};
let validatePasswordRepeat = (rule, value, callback) => {
    // 如果模块值为login, 直接通过
    if (model.value === 'login') {
        callback();
    }
    if (value === '') {
        callback(new Error('请再次输入密码'));
    } else if (value !== loginForm.passWord) {
        callback(new Error('与密码不一致'));
    } else {
        callback();
    }
};
let validateCode = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请输入验证码'));
    } 
    // else if (codeRule(value)) {
    //     return callback(new Error('验证码为6位的数字或字母'));
    // } 
    else {
        callback()
    }
};

 // ----------------------------------- 声明数据 -----------------------------------
 // 登录注册模块标识
 const model = ref('login');

// 登录注册按钮
const menuTab = reactive([
    { 'txt': '登陆', 'isCurrent': true, 'type': 'login' },
    { 'txt': '注册', 'isCurrent': false, 'type': 'register' }
]);
// 表单内容
const loginForm = reactive({
    userName: '',
    passWord: '',
    passWordRepeat: '',
    code: ''
});
// 登录按钮属性
const loginButton = reactive({
    disabled: true
});
// 验证码按钮属性
const codeButton = reactive({
    text: '获取验证码',
    disabled: false
});
// 表单验证规则
const rules = reactive({
    userName: [{
        validator: validateUserName, trigger: 'blur'
    }],
    passWord: [{
        validator: validatePassword, trigger: 'blur'
    }],
    passwordRepeat: [{
        validator: validatePasswordRepeat, trigger: 'blur'
    }]
    // ,
    // code: [{
    //     validator: validateCode, trigger: 'blur'
    // }]
});
// 倒计时
const timer = ref(null);
 // ----------------------------------- 声明函数 -----------------------------------
//切换模块
const toggleMenu = (item) => {
    menuTab.forEach(i => {
        i.isCurrent = false;
    });
    item.isCurrent = true;
    model.value = item.type;
    clearCountDown(); // 清除倒计时
    resetFromData(); // 清除表单数据
}
// 清除表单数据
const resetFromData = (() => {
    loginFromRef.value.resetFields();
});
// 清除倒计时
const clearCountDown = (() => {
    updateCodeBtn({
        status: false,
        text: '获取验证码'
    })
    clearInterval(timer.value)
});
// 验证码按钮属性更新
const updateCodeBtn = ((params) => {
    codeButton.text = params.text
    codeButton.disabled = params.disabled
});
// 提交表单
const submitForm =((formName)=>{
    toLogin()
    // refs[formName].validate((valid)=>{
    //     if(valid){
    //         model.value == "login"? toLogin():register()
    //     }else {
    //         return false;
    //     }
    // })
})
const toLogin = (()=>{
    var param = {
        userName:loginForm.userName,
        passWord:loginForm.passWord
    }
    login(param).then(res=>{
      ElMessage({
        message: '登录成功',
        type: 'success',
      })
        console.log("登录信息",res)
      router.push("/home")
    }).catch(error=>{
        console.log("登录失败",error)
      ElMessage({
        message: '登录失败',
        type: 'error',
      })
    })
})


</script>



<style lang="scss" scoped>
#login {
    height: 100vh;
    width: 100vw;
    background-color: #344a5f;
}

.login-wrapper {
    width: 330px;
    margin: auto;
    // padding-top: calc(100vh / 7);
    // background: #fff;
}

.menu-tab {
    text-align: center;

    li {
        display: inline-block;
        width: 88px;
        line-height: 36px;
        color: white;
        font-size: 14px;
        border-radius: 2px;
        cursor: pointer;

        &.current {
            background-color: rgba(0, 0, 0, 0.1);
            background-color: gray;
        }
    }
}

.login-form {
    margin-top: 20px;

    .login-form-item {
        margin-bottom: 13px;
    }

    .block {
        display: block;
        width: 100%;
    }

    .login-btn {
        margin-top: 20px;
    }

    label {
        display: block;
        margin-bottom: 3px;
        font-size: 14px;
        color: #fff;
    }

    input {
        display: inline-block;
        width: 100%;
    }
}
</style>
